#include "KeyboardController.h"
#include "Application.h"
#include <math.h>  

cat::KeyboardController::KeyboardController(cat::Tank& tank)
	: cat::KeyboardController::ControllerBase(tank),
	_isModified(false)
{
	
}

cat::KeyboardController::~KeyboardController(void)
{
}

void cat::KeyboardController::treatEvent(sf::Event& event)
{
	sf::RenderWindow& window = cat::Application::current().getWindow();

	if(event.type == sf::Event::MouseButtonPressed)
	{
		if(event.mouseButton.button == sf::Mouse::Left)
		{
			_tank.fire();
		}
	}

	// Push controller if updates occured
	if(	(event.type == sf::Event::KeyPressed || event.type == sf::Event::KeyReleased) && 
			(event.key.code == sf::Keyboard::Left
			|| event.key.code == sf::Keyboard::Right
			|| event.key.code == sf::Keyboard::Up
			|| event.key.code == sf::Keyboard::Down))
	{
		_isModified = true;
	}

	// translation
	{
		_controlPosition.x = 0;
		_controlPosition.y = 0;
		if(sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
		{
			_controlPosition.x--;
		}

		if(sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
		{
			_controlPosition.x++;
		}

		if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
		{
			_controlPosition.y--;
		}

		if(sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
		{
			_controlPosition.y++;
		}

		// TODO factorize
		if(_controlPosition.x == 0 && _controlPosition.y == 0)
		{
			_tank.setVelocity(0);
		}
		else
		{
			double angle = atan2(_controlPosition.y, _controlPosition.x);
			double velocity = 1;

			_tank.move(angle, velocity);
		}
	}
}

void cat::KeyboardController::think(void)
{
	sf::RenderWindow& window = cat::Application::current().getWindow();

	// cannon
	{
		sf::Vector2i mousePosition = sf::Mouse::getPosition(window);
		_tank.turretTarget(mousePosition.x, mousePosition.y);
	}

	if(_isModified)
	{
		cat::Application::current().pushControllerRequieringSynchronization(this);
	}

	_isModified = false;
}